package com.zhangdi.demo.jdbc;

import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;
import java.util.Properties;

/**
 * @author zhangdi
 * @version 1.0
 * @date 2022.6.30 17:30
 */

public class ConsistentHashTableAlgorithm extends AbstractConsistentHashAlgorithm {
    @Override
    public String getType() {
        return "CONSISTENT_HASH_TB";
    }

    @Override
    public void init(Properties properties) {
        //分表需要一致性哈希吗？ 需要虚拟吗？
//        0 1
//            0-0 0-1 0-2 0-3 1-0 1-1 1-2 1-3
//            //成本方面 需要
//        50
//        0
//                1
//                        2
//        7328123471+--3
    }

    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Long> preciseShardingValue) {//需要和db算法一样吗 得到hash后再取余？
//        long idHashCode = hash(preciseShardingValue.getValue());
//        SortedMap<Long, String> hitServerMap = virtualServers.tailMap(idHashCode);
//        String targetName = null;
//        if (hitServerMap.isEmpty()) {
//            targetName = preciseShardingValue.getDataNodeInfo().getPrefix() + virtualServers.firstKey() % collection.size();
//        } else {
//            targetName = preciseShardingValue.getDataNodeInfo().getPrefix() + hitServerMap.firstKey() % collection.size();
//        }
//
        String targetName = preciseShardingValue.getDataNodeInfo().getPrefix() + preciseShardingValue.getValue() % collection.size();
        for (String item : collection) {
            if (item.equals(targetName)) {
                return item;
            }
        }

        return null;
    }
}
